/*
 * Copyright (c) 2022-2023 cetcclout Co., Ltd All rights reserved.
 * Sensor Adapter is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package com.cetccloud.cimp.common.util;

import com.google.common.base.Charsets;
import com.google.common.hash.Hashing;
import org.apache.commons.lang3.RandomStringUtils;

import java.util.Base64;


/**
 * 密码工具
 */
public class SecurityUtil {


    /**
     *
     * @return 生成密码需要的盐
     */
    public static String getSalt(){
        return RandomStringUtils.randomAlphabetic(64);
    }

    /**
     *
     * @return 生成密码需要的盐
     */
    public static String getSalt(String userName){
        return Base64.getEncoder().encodeToString(userName.getBytes());
    }

    /**
     *
     * @param salt
     * @param pwdPlain
     * @return sha256
     */
    public static String sha256(String salt,String pwdPlain){
        return Hashing.sha256().newHasher().putString(salt + pwdPlain, Charsets.UTF_8).hash().toString();
    }

    public static boolean isOk(String salt,String pwdPlain,String password){
        String current = Hashing.sha256().newHasher().putString(salt + pwdPlain, Charsets.UTF_8).hash().toString();
        return current.equals(password);
    }

    public static void main(String[] args) {
        String salt = getSalt("admin");
        System.out.println(salt);
        System.out.println(sha256(salt,"123456"));
    }

}
